import { FC, useState } from "react";
import { produce } from "immer";
import QuestionCard from "./components/QuestionCard";

const List: FC = () => {
  const [questionList, setQuestionList] = useState([
    { id: "q1", title: "问卷1", isPublished: true },
    { id: "q2", title: "问卷2", isPublished: false },
    { id: "q3", title: "问卷3", isPublished: true },
    { id: "q4", title: "问卷4", isPublished: false },
  ]);

  function add() {
    const r = Math.random().toString().slice(-3);
    // setQuestionList([
    //   ...questionList,
    //   { id: "q" + r, title: "问卷" + r, isPublished: false },
    // ]);
    setQuestionList(
      produce((draft) => {
        draft.push({ id: "q" + r, title: "问卷" + r, isPublished: false });
      })
    );
  }

  function deleteQuestion(id: string) {
    setQuestionList(questionList.filter((q) => q.id !== id));
  }

  function publishQuestion(id: string) {
    setQuestionList(
      questionList.map((q) => (q.id === id ? { ...q, isPublished: true } : q))
    );
  }

  return (
    <div>
      <h1>问卷列表</h1>
      <div>
        {questionList.map((question) => {
          const { id, title, isPublished } = question;
          return (
            <QuestionCard
              key={id}
              id={id}
              title={title}
              isPublished={isPublished}
              deleteQuestion={deleteQuestion}
              publishQuestion={publishQuestion}
            />
          );
        })}
      </div>
      <button onClick={add}>新增</button>
    </div>
  );
};
export default List;
